//
//  YBMineOrderListVC.swift
//  Moonlight
//
//  Created by Penlon Kim on 2023/7/1.
//  Copyright © 2023 Moonlight Game Streaming Project. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyJSON
import HandyJSON
import JXPagingView

class YBMineOrderListVC: BaseVC {
    
    deinit {
        listViewDidScrollCallback = nil
    }
    
    fileprivate var pageNo = 1
    fileprivate var pageSize = 10
    
    private var listViewDidScrollCallback: ((UIScrollView) -> ())?
    
    private let itemType: YBMineOrderVC.ItemType
    
    init(type: YBMineOrderVC.ItemType) {
        itemType = type
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .lightGray248Dark17
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        // 占位图
        showEmptyData(self.tableView)
        // 开始请求
        tableView.bk_refreshing()
    }
    
    // MARK: - lazy
    lazy var vm: YBMineViewModel = {
        let vm = YBMineViewModel()
        return vm
    }()
    
    private lazy var tableView: UITableView = {
        let tv = UITableView(frame: .zero, style: .grouped)
        tv.backgroundColor = .lightGray242Dark17
        tv.estimatedRowHeight = 44
        tv.rowHeight = UITableView.automaticDimension
        tv.separatorStyle = .none
        tv.showsVerticalScrollIndicator = false
        tv.tableFooterView = UIView()
        tv.delegate = self
        tv.dataSource = self
        if #available(iOS 15.0, *) {
            tv.sectionHeaderTopPadding = 0
        }
        tv.bk_addRefreshHeader { [weak self] in
            self?.headerRefresh()
        }
        tv.bk_addLoadMoreFooter { [weak self] in
            self?.footerRefresh()
        }
        tv.register(cellWithClass: YBMineOrderCell.self)
        return tv
    }()
    
    
    func headerRefresh() {
        pageNo = 1
        // 请求数据
        let params = ["pageNo": pageNo.stringValue(),
                      "pageSize": pageSize.stringValue()] as [String : Any]
        
        vm.req_OrderList(params) { [weak self] ok, obj, msg, code in
            self?.tableView.bk_endMJRefresh()
            if ok {
                guard let js = obj as? JSON,
                      let data = js[NetDataKey]["list"].arrayObject,
                      let total = js[NetDataKey]["total"].int,
                      let models = [YBOrderModel].deserialize(from: data) as? [YBOrderModel] else { return }
                
                if (total / self!.pageSize) > self!.pageNo {
                    self?.tableView.bkFooter?.isHidden = false
                }
                self?.vm.oderModels = models
                self?.tableView.reloadData()
            } else {
                HintTool.toast(msg)
            }
        }
    }
    
    func footerRefresh() {
        pageNo += 1
        // 请求数据
        let params = ["pageNo": pageNo.stringValue(),
                      "pageSize": pageSize.stringValue()] as [String : Any]
        
        vm.req_OrderList(params) { [weak self] ok, obj, msg, code in
            self?.tableView.bk_endMJRefresh()
            if ok {
                guard let js = obj as? JSON,
                      let data = js[NetDataKey]["list"].arrayObject,
                      let models = [YBOrderModel].deserialize(from: data) as? [YBOrderModel] else { return }
                self?.vm.oderModels.append(contentsOf: models)
                self?.tableView.reloadData()
            } else {
                HintTool.toast(msg)
            }
        }
    }
}

// MARK: - UITableView代理
extension YBMineOrderListVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return vm.oderModels.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YBMineOrderCell.self, for: indexPath)
        let model = vm.oderModels[indexPath.row]
        cell.updateCell(by: model)
        cell.onPay = { [weak self] goodsid in
            let buyVC = YBCloudComputerBuyVC(goodsId: goodsid)
            self?.navigationController?.pushViewController(buyVC, animated: true)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.listViewDidScrollCallback?(scrollView)
    }
    
}

// MARK: - JXPagingViewListViewDelegate代理
extension YBMineOrderListVC: JXPagingViewListViewDelegate {
    
    func listView() -> UIView {
        return view
    }
    
    func listScrollView() -> UIScrollView {
        return tableView
    }
    
    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        self.listViewDidScrollCallback = callback
    }
    
}
